class RSATool {
  constructor (NodeRSA) {
    this.NodeRSA = NodeRSA;
  }

  /**
   * 获取秘钥
   * @returns {{priKey: *, pubKey: *}}
   */
  createKey () {
    const newKey = new this.NodeRSA({
      b: 1024,
      encryptionScheme: 'pkcs1'
    });
    const pubKey = newKey.exportKey('pkcs8-public'); // 公钥,
    const priKey = newKey.exportKey('pkcs8-private'); // 私钥

    return {
      pubKey,
      priKey
    };
  }

  /**
   * 加密
   * @param message
   * @param pubKey
   * @returns {*}
   */
  encrypt (message, pubKey) {
    const pub = new this.NodeRSA(pubKey, { encryptionScheme: 'pkcs1' });

    return pub.encrypt(message, 'base64');
  }

  /**
   * 解密
   * @param encryptTxt
   * @param privateK
   * @returns {*}
   */
  decrypt (encryptTxt, privateK) {
    const pri = new this.NodeRSA(privateK, { encryptionScheme: 'pkcs1' });

    const txt = pri.decrypt(encryptTxt, 'utf8');
    let re = null;
    try {
      re = JSON.parse(txt);
    } catch (e) {
      console.log('解密后的数据无法转换为 JSON');
      re = txt;
    }
    return re;
  }
}

RSATool.pubKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAldxz6cAy5GlAfa4nv/lp
t4sWcxp7XsSF9Qgi/W/b3xqI+tfx/2dGSAEaHOPdjoTG0HZRyfzZ9rjqdNjyUCJC
j9OmTlD6onmAuXrQtx5uwXBwwdxDvRiu5anHJBTLRBORTXIYA5BeROoMkEHdycdN
/j44k9cw9LlI9X/Y14UQqy12vRj4xRdQ20fJZ3f0Gq3BE40UwPUUhtO4GjiTzDkV
ZD5dpThTrhF2MQRjb78DBcizB+4sjvdd/bP+s5nBfRYRSN8OvYTGmW/iOCY0sR0r
XM7HnmVh9UybYBk5LpkIfkmI7qOQbgPQlJ/HWIthrMXWsfFmj4x+zM+mOY4IST4C
BwIDAQAB
-----END PUBLIC KEY-----`;

RSATool.priKey = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFA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